package com.domi.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.domi.bean.RestfulResponse;
import com.domi.bean.RestfulResponse.ResponseCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        RestfulResponse error = null;
        if (e instanceof FlowException) {
            error = RestfulResponse.create(ResponseCode.ERROR, "服务限流", "兜底数据");
        } else if (e instanceof DegradeException) {
            error = RestfulResponse.create(ResponseCode.ERROR, "服务降级", "兜底数据");
        } else if (e instanceof ParamFlowException) {
            error = RestfulResponse.create(ResponseCode.ERROR, "热点限流", "兜底数据");
        } else if (e instanceof SystemBlockException) {
            error = RestfulResponse.create(ResponseCode.ERROR, "系统规则不通过", "兜底数据");
        } else if (e instanceof AuthorityException) {
            error = RestfulResponse.create(ResponseCode.ERROR, "授权规则不通过", "兜底数据");
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-type", "application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        new ObjectMapper().writeValue(response.getWriter(), error);
    }

}